package new_clue

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/user_db"
	"hft/Http/Services/new_clue/clue_dao"
	"hft/Http/Services/new_clue/clue_model"
	"hft/Http/Services/new_clue/clue_utils"
	"hft/Http/Services/user/user_utils"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"hft/tools"
	"hft/tools/front_user"
	"strings"

	"gorm.io/gorm"
)

// 线索留资
type ActivityClue struct{}

// 留线索
func (*ActivityClue) Add(data *clue_model.ActivityClue, token string, city int, ip string, port int) (result *clue_model.ClueRes, err error) {
	newUserPhone := tools.CorrectPhone(data.Phone)
	if claims, ok := clue_utils.Jwt(token); !ok { //验证没过
		if user, err := clue_dao.FindUser(newUserPhone, city); err != nil {
			// 客户不存在就创建新的客户
			if err := clue_dao.CreateUser(city, ip, *data, port); err != nil {
				return nil, err
			}
			// go clue_dao.SendMessageToBroker(global.OC_DB, data.Phone, uint(data.LouID), city)
		} else {
			// 存在就添加线索
			var activity, err = clue_dao.FindActivity(data.ActivityCode, data.IsLouPanActivity)
			if err != nil {
				return nil, err
			}
			var lou *admin.LouPan
			var region *admin.Region
			var regionName string
			var louName string
			if data.LouID == 0 {
				global.OC_DB.First(&region, city)
				regionName = region.Name
			} else {
				global.OC_DB.First(&lou, data.LouID)
				regionName = user_utils.GetBelongName(lou.BelongName)
				louName = lou.Name
			}
			var clue = clue_dao.GenerateSingleClue(data, ip, activity.Title, port, regionName, louName)
			clue.UserID = user.ID
			global.OC_DB.Create(&clue)
		}
		newPhone := utils.DesensitizePhoneNumber(data.Phone)
		var res = &clue_model.ClueRes{Skip: true, Phone: data.Phone, TuoPhone: newPhone}
		// 发送验证码
		SendValid(newUserPhone)
		go clue_dao.SendMessageToBroker(global.OC_DB, data.Phone, uint(data.LouID), city)
		return res, nil
	} else {
		var activity, err = clue_dao.FindActivity(data.ActivityCode, data.IsLouPanActivity)
		if err != nil {
			return nil, err
		}
		// 寻找客户
		var user *user_db.User
		var clue *user_db.Clue
		var res = &clue_model.ClueRes{Skip: false, Phone: "", TuoPhone: ""}
		global.OC_DB.First(&user, claims.ID)
		newPhone := utils.DesensitizePhoneNumber(user.Phone)
		res.Phone = user.Phone
		res.TuoPhone = newPhone
		if tools.CheckPhoneNumber(data.Phone) != 3 {
			var user1 *user_db.User
			if err = global.OC_DB.Where("phone = ? AND city = ?", data.Phone, city).First(&user1).Error; err != nil {
				// 客户不存在就创建新的客户
				if err := clue_dao.CreateUser(city, ip, *data, port); err != nil {
					return nil, err
				}
			} else {
				var lou *admin.LouPan
				var region *admin.Region
				var regionName string
				var louName string
				if data.LouID == 0 {
					global.OC_DB.First(&region, city)
					regionName = region.Name
				} else {
					global.OC_DB.First(&lou, data.LouID)
					regionName = user_utils.GetBelongName(lou.BelongName)
					louName = lou.Name
				}
				clue = clue_dao.GenerateSingleClue(data, ip, activity.Title, port, regionName, louName)
				clue.UserID = uint(user1.ID)
				global.OC_DB.Create(&clue)
			}

			if user.Phone != data.Phone {
				res.Skip = true
				SendValid(newUserPhone)
				res.Phone = data.Phone
				res.TuoPhone = utils.DesensitizePhoneNumber(data.Phone)
			}

		} else {
			var lou *admin.LouPan
			var region *admin.Region
			var regionName string
			var louName string
			if data.LouID == 0 {
				global.OC_DB.First(&region, city)
				regionName = region.Name
			} else {
				global.OC_DB.First(&lou, data.LouID)
				regionName = user_utils.GetBelongName(lou.BelongName)
				louName = lou.Name
			}
			data.Phone = user.Phone
			clue = clue_dao.GenerateSingleClue(data, ip, activity.Title, port, regionName, louName)
			clue.UserID = uint(claims.ID)
			global.OC_DB.Create(&clue)
		}
		go clue_dao.SendMessageToBroker(global.OC_DB, data.Phone, uint(data.LouID), city)
		return res, nil
	}
}

// 发送验证码
func SendValid(phone string) {
	switch tools.CheckPhoneNumber(phone) {
	case 0:
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsModel)
	case 1:
		// newPhone := tools.IsAddRegion(phone, 1)
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsHKModel)
	case 2:
		// newPhone := tools.IsAddRegion(phone, 2)
		tools.AliyunSmsTool.SendValid(global.OC_CONFIG.AliyunSms.UserSend, phone, global.OC_CONFIG.AliyunSms.SmsHKModel)
	}
}

// 微聊登录
func (*ActivityClue) ChatLogin(ip string, port int, phone string, lou_id int, code string, sid int) (string, error) {
	correctPhone := tools.CorrectPhone(phone)
	if err := tools.AliyunSmsTool.VerifyValid(global.OC_CONFIG.AliyunSms.UserSend, correctPhone, code); err != nil {
		return "", err
	}
	var user *user_db.User
	var city *admin.Region
	var lou_name string
	var region_name string
	var lou *admin.LouPan
	err := global.OC_DB.First(&city, sid).Error
	if err != nil {
		return "", errors.New(e.RegionNotFound)
	}
	err = global.OC_DB.First(&lou, lou_id).Error
	if err != nil {
		lou_name = "公共页面"
		region_name = city.Name
	} else {
		lou_name = lou.Name
		var belongStr = strings.Split(lou.BelongName, "-")
		if len(belongStr) == 3 {
			region_name = belongStr[len(belongStr)-1]
		} else if len(belongStr) == 4 {
			region_name = belongStr[len(belongStr)-2]
		} else {
			region_name = city.Name
		}
	}
	err = global.OC_DB.Where("phone = ?", phone).Where("city = ?", sid).First(&user).Error
	var uid = tools.GenUUID2()
	if err != nil {
		var newUser = &user_db.User{
			UUID:        uid,
			Phone:       phone,
			City:        sid,
			CityLink:    fmt.Sprintf("%v%v,", city.Link, city.ID),
			CityName:    city.Name,
			Username:    "",
			WeChat:      "",
			Alternative: "",
			IntendLou:   lou_name,
			IntendPrice: "",
			IntendLouID: lou.ID,
			RemarkInfo:  "",
			ManagerID:   0,
			ManagerName: "",
			IsValid:     true,
			IsShield:    false,
			Clues: []*user_db.Clue{
				&user_db.Clue{
					ActivityName: "微聊",
					ActivityCode: 22,
					LouPanID:     lou_id,
					LouName:      lou_name,
					Port:         port,
					RegionName:   region_name,
					OriginType:   2,
					IP:           ip,
				},
			},
		}
		err = global.OC_DB.Create(&newUser).Error
		if err != nil {
			return "", errors.New(e.ErrorInfo)
		}
		var newTempUser *user_db.User
		err = global.OC_DB.Select("uuid,id").Where("uuid = ?", uid).First(&newTempUser).Error
		if err != nil {
			return "", errors.New(e.UserNotFound)
		}
		var j = front_user.NewJWT()
		var baseClaims = &front_user.BaseClaims{ID: int(newTempUser.ID), UUID: newTempUser.UUID}
		token, _ := j.CreateToken(j.CreateClaims(*baseClaims, "36135d", "365d"))
		go clue_dao.SendMessageToBroker(global.OC_DB, phone, lou.ID, sid)
		return token, nil
	} else {
		var clue = &user_db.Clue{
			UserID:       user.ID,
			ActivityName: "微聊",
			ActivityCode: 22,
			LouPanID:     lou_id,
			LouName:      lou_name,
			Port:         port,
			RegionName:   region_name,
			OriginType:   2,
			IP:           ip,
		}
		err = global.OC_DB.Create(&clue).Error
		if err != nil {
			return "", errors.New(e.ErrorInfo)
		}
		var j = front_user.NewJWT()
		var baseClaims = &front_user.BaseClaims{ID: int(user.ID), UUID: user.UUID}
		token, _ := j.CreateToken(j.CreateClaims(*baseClaims, "36135d", "365d"))
		go clue_dao.SendMessageToBroker(global.OC_DB, phone, lou.ID, sid)
		return token, nil
	}

}

// 验证客户
func ValidUser(data *clue_model.PhoneReq, city int) (token string, err error) {
	newPhone := tools.CorrectPhone(data.Phone)
	if err := tools.AliyunSmsTool.VerifyValid(global.OC_CONFIG.AliyunSms.UserSend, newPhone, data.Code); err != nil {
		return "", err
	} else {
		// 创建新的token
		var user *user_db.User
		if err = global.OC_DB.Transaction(func(tx *gorm.DB) error {
			err = tx.Where("phone = ? AND city = ?", newPhone, city).First(&user).Error
			if err != nil {
				return errors.New(e.UserNotFound)
			}
			err = clue_dao.AddActivityNum(data.ActivityCode)
			if err != nil {
				return err
			}
			err = tx.Model(&user_db.User{}).Where("uuid = ?", user.UUID).Update("is_valid", 1).Error
			if err != nil {
				return err
			}
			return nil
		}); err != nil {
			return "", err
		} else {
			var j = front_user.NewJWT()
			var baseClaims = &front_user.BaseClaims{ID: int(user.ID), UUID: user.UUID}
			token, _ = j.CreateToken(j.CreateClaims(*baseClaims, "36135d", "365d"))
			return token, nil
		}
	}
}

var ActivityClueService = new(ActivityClue)
